<template>
    <el-dialog :title="type == 'add' ? '添加数据库' : '修改数据库'" v-model="visible" width="400px">
        <el-form :model="ruleForm" :rules="rules" ref="formRef" label-width="100px" >
            <el-form-item label="标题" prop="title">
                <el-input type="text" v-model="ruleForm.title"></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="type">

                <el-select @change="handleOption" v-model="ruleForm.type" size="small">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>

            </el-form-item>
            <el-form-item label="host" prop="host">
                <el-input type="text" v-model="ruleForm.host"></el-input>
            </el-form-item>

            <el-form-item label="port" prop="port">
                <el-input type="number" v-model="ruleForm.port"></el-input>
            </el-form-item>

            <el-form-item label="dbName" prop="dbName">
                <el-input type="text" v-model="ruleForm.dbName"></el-input>
            </el-form-item>

            <el-form-item label="dbUser" prop="dbUser">
                <el-input type="text" v-model="ruleForm.dbUser"></el-input>
            </el-form-item>
            <el-form-item label="dbPass" prop="dbPass">
                <el-input type="text" v-model="ruleForm.dbPass"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="visible = false">取 消</el-button>
                <el-button type="primary" @click="testConnect">测试连接</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts">
    import * as db_context from '@/models/db_context'
    import {
        reactive,
        ref,
        toRefs
    } from 'vue'

    import {
        ElMessage
    } from 'element-plus'
    const {
        Sequelize
    } = window.require('sequelize-typescript');
    export default {
        name: 'DialogAddDb',
        props: {
            type: String, // 用于判断是添加还是编辑
            reload: Function // 添加或修改完后，刷新列表页
        },
        setup(props: any) {
            const formRef = ref < any > (null)
            const state = reactive({
                visible: false,
                tId: "0",
                isTest:0,
                options: [{
                    value: 'postgres',
                    label: 'postgres'
                }, {
                    value: 'mysql',
                    label: 'mysql'
                }],
                orderStatus: '', // 订单状态
                ruleForm: {
                    title: '',
                    type: 'mysql',
                    host: '',
                    port: '',
                    dbName: '',
                    dbUser: '',
                    dbPass: ''
                },
                rules: {
                    title: [{
                        required: 'true',
                        message: '名称不能为空',
                        trigger: ['change']
                    }],
                    host: [{
                        required: 'true',
                        message: 'host不能为空',
                        trigger: ['change']
                    }],
                    port: [{
                        required: 'true',
                        message: 'port不能为空',
                        trigger: ['change']
                    }],
                    dbName: [{
                        required: 'true',
                        message: 'dbName不能为空',
                        trigger: ['change']
                    }],
                    dbUser: [{
                        required: 'true',
                        message: 'dbUser不能为空',
                        trigger: ['change']
                    }]
                },
                id: ''
            })
            // 获取详情
            const getDetail = (id: string) => {
                console.log(id);
                state.tId = id;
                //state.tId = results;

                db_context.GenDb.getById < db_context.Project > (Number.parseInt(state.tId))
                    .then((results: any) => {
                        state.ruleForm = results;
                    });
            }
            // 开启弹窗
            const open = (id: string) => {
                state.visible = true
                if (id) {
                    state.id = id
                    // 如果是有 id 传入，证明是修改模式
                    getDetail(id)
                } else {
                    state.ruleForm = {
                        title: '数据库',
                        type: 'mysql',
                        host: '127.0.0.1',
                        port: '3306',
                        dbName: 'test',
                        dbUser: 'root',
                        dbPass: '123456'
                    }

                }
            }
            // 触发过滤项方法
            const handleOption = () => {
                console.log('gggggggggg')
            }
            const testConnect = () => {
                const sequelize = new Sequelize(state.ruleForm.dbName, state.ruleForm.dbUser, state.ruleForm
                    .dbPass, {
                        host: state.ruleForm.host,
                        port: state.ruleForm.port,
                        dialect: state.ruleForm.type,
                        pool: {
                            max: 5,
                            min: 0,
                            idle: 10000
                        },
                        timezone: '+08:00'
                    });

                sequelize.authenticate().then(() => {
                        ElMessage.success('测试连接成功');
                        state.isTest=1;
                    })
                    .catch(() => {
                        ElMessage.error('Unable to connect to the database:')

                    });

            }

            // 关闭弹窗
            const close = () => {
                state.visible = false
            }
            const submitForm = () => {
                if(state.isTest==0){
                  ElMessage.error('请先测试连接');
                   return;
                }
                formRef.value.validate((valid: boolean) => {
                    if (valid) {
                        if (props.type == 'add') {
                            // 添加方法
                            const formvalue: any = state.ruleForm;
                            db_context.GenDb.createItem < db_context.GenDb > (formvalue)
                                .then(results => {
                                    console.log('resultsxxxxx:', results);

                                    ElMessage.success('添加成功')
                                    state.visible = false
                                    // 接口回调之后，运行重新获取列表方法 reload
                                    if (props.reload) props.reload()
                                });




                        } else {

                            // 添加方法
                            const formvalue: any = state.ruleForm;
                            db_context.GenDb.updateItemById < db_context.GenDb > (formvalue, Number
                                    .parseInt(state.tId))
                                .then(results => {
                                    console.log('resultsxxxxx:', results);

                                    ElMessage.success('修改成功')
                                    state.visible = false
                                    // 接口回调之后，运行重新获取列表方法 reload
                                    if (props.reload) props.reload()
                                });



                        }
                    }
                })
            }
            return {
                ...toRefs(state),
                open,
                close,
                formRef,
                handleOption,
                testConnect,
                submitForm
            }
        }
    }
</script>